package cn.wolfcode.trip.api.controller;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JsonResult;
import cn.wolfcode.trip.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @author pengq
 */
@RestController
@RequestMapping("/sessions")
public class LoginController {
    @Autowired
    private IUserService userService;

    /**
     * 登录接口
     * 1.资源sessions/{user}
     * 2.方式post
     * 3.json对象
     *
     * @param user
     * @return JsonResult
     */
    @PostMapping
    public JsonResult login(User user, String verify, HttpSession session) {
        JsonResult json = new JsonResult();
        try {
            User temp = userService.login(user, verify);
            // 返回给客户端，让客户端存储起来
            json.setData(temp);

            //登录后删除 session 验证码
            session.removeAttribute("phoneNumber");
            session.removeAttribute("verify");
        } catch (Exception e) {
            e.printStackTrace();
            json.mark(e.getMessage());
        }
        return json;
    }

    /**
     * 注销接口
     * 1.资源 sessions
     * 2.方式 delete
     */
    @DeleteMapping
    public void logout() {
        // 获取session，销毁
        UserContext.getSession().invalidate();
    }

}
